// pages/mine/mine.js
const app = getApp();// 云：add this before every page //
Page({
  data: {
    safeHeight: app.globalData.tabBarHeight + app.globalData.safeBottom, // 云：add this before every page //
    // safeTop: app.globalData.safeTop
    safeTop: 0,

    accessToken:"",
    userInfo: {},
    mineStatistic:{
      learnedToday: "-",
      learned: "-",
      rank: "-"
    },

    mineCells:[
        {
          imagePath1:"/image/mine/1-clock.png",
          text:"学习历史",
          imagePath2:"/image/mine/5-link.png",
          id: 0
        },
        {
          imagePath1:"/image/mine/2-star.png",
          text:"我的收藏",
          imagePath2:"/image/mine/5-link.png",
          id: 1
        },
        {
          imagePath1:"/image/mine/3-comment.png",
          text:"我的反馈",
          imagePath2:"/image/mine/5-link.png",
          id: 2
        },
        {
          imagePath1:"/image/mine/4-service.png",
          text:"联系我们",
          imagePath2:"/image/mine/5-link.png",
          id: 3
        },
      ],
  },

  initMine(){
    let accessToken = wx.getStorageSync('accessTokenData').accessToken
    console.log("初始化函数取出的accesstoken是：",wx.getStorageSync('accessTokenData'))
    if(accessToken){
      wx.showLoading({
        title: '正在登录',
        mask: true
      })
      console.log("本地存储的accessToken是：", accessToken)
      this.setData({
        accessToken: accessToken,
      })
      this.getMineData() // 根据accessToken获取用户信息
    }
    else{
      console.log('读取accessToken失败')
      this.setData({
        showGetPhoneNumber: true
      })
      wx.showToast({
        title: '请前往“我的”授权登录！',
        icon: "none",
        duration: 2000
      })
    }
  },

  getMineData(){
    wx.request({
      // url: this.globalData.url + '/login',
      url: app.globalData.server+'/app-api/member/user/get',
      header:{
        "Authorization": 'Bearer '+this.data.accessToken
      },
      method: "GET",
      success: (res) => {
        console.log("根据accessToken获取的用户信息是：",res)
        const data = res.data;
        if(!data.data){

          wx.showToast({
            title: '登录过期，请重新授权登录！',
            icon: "none",
            duration: 2000
          })

          wx.removeStorageSync('accessTokenData')
          this.setData({
            accessToken: "",
          })
          this.initMine()
        }
        else{
          if(!data.data.avatar||!data.data.nickname){
            wx.navigateTo({
              url: '/pages/getuserinfo/index',
            })
          }
          else{
            this.setData({
              userInfo: data.data,
            })
            this.getUserStatistic()
          }
        }
      },
      fail: (err) => {
        wx.showModal({
          title: '提示',
          content: JSON.stringify(err),
        })
        console.log(err);
      },
      complete:()=>{
        wx.hideLoading();
      }
    })
  },

  getUserStatistic(){
    wx.request({
      // url: this.globalData.url + '/login',
      url: app.globalData.server+'/app-api/epg/user/statistic',
      header:{
        "Authorization": 'Bearer '+this.data.accessToken,
      },
      method: "GET",
      success: (res) => {
        console.log("根据accessToken获取的用户学习数据是：",res)
        if(res.data.code===0){
          let mineStatisticTemp = res.data.data
          mineStatisticTemp.rank = parseInt(mineStatisticTemp.rank*100)
          this.setData({
            mineStatistic: mineStatisticTemp,
          })
        }
        
      },
      fail: (err) => {
        wx.showModal({
          title: '提示',
          content: JSON.stringify(err),
          success: function (res) {
            if (res.confirm) {//这里是点击了确定以后
              console.log('用户点击确定')
            } else {//这里是点击了取消以后
              console.log('用户点击取消')
            }
          }
        })
        console.log(err);
      },
      complete:()=>{
        wx.hideLoading();
      }
    })
  },

  // 获取手机号code
  getPhoneNumber (e) {
    let loginCode=""
    let phoneCode=""
    console.log("手机号code是: ", e.detail)
    if(typeof(e.detail.code) == "undefined"){
      console.log("授权失败！")
    }
    else{
      phoneCode=e.detail.code
      wx.showLoading({
        title: '正在登录',
        mask: true
      })
      // 登录
      wx.login({
        success: res => {
          console.log("登录成功：",res)
          loginCode = res.code
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          wx.request({
            // url: this.globalData.url + '/login',
            url: app.globalData.server+'/app-api/member/auth/weixin-mini-app-login',
            data: {
              loginCode: loginCode,
              phoneCode: phoneCode
            },
            method: "POST",
            success: (res) => {
              console.log("获取的accessToken是：",res);
              console.log("现在时间是：",Date.now())
              const accessToken = res.data.data.accessToken;
              wx.setStorageSync("accessTokenData", res.data.data);
              this.setData({
                accessToken: accessToken,
              })
              this.getMineData() // 根据accessToken获取用户信息
            },
            fail: (err) => {
              console.log("后台请求登录失败",err);
            },
            complete: () => {
              // wx.hideLoading();
            }
          })
        },
      })
    }
    
  },

  tabMineCells(e){
    console.log(e.currentTarget.dataset.id, this.data.accessToken)
    let currentId = e.currentTarget.dataset.id
    if(this.data.accessToken){
      // 解决 e.currentTarget.dataset.id为空，参考：https://www.bbsmax.com/A/VGzlLNE7zb/
      if(currentId==0){
        wx.switchTab({
          url: '/pages/course/course',
        })
        app.globalData.history = 1;
        app.globalData.switchTabFalg = 1
        console.log("点击了我的页面的学习历史!")
      }
      else if(currentId==1){
        wx.navigateTo({
          url: '/pages/like/like',
        })
      }
      else if(currentId==2){
        wx.navigateTo({
          url: '/pages/minefeedback/minefeedback',
        })
      }
      else{
        wx.navigateTo({
          url: '/pages/contactus/contactus',
        })
      }
    }
    else{
      if(currentId==3){
        wx.navigateTo({
          url: '/pages/contactus/contactus',
        })
      }
      else{
        wx.showToast({
          title: '请前往“我的”授权登录！',
          icon: "none",
          duration: 2000
        })
      }
    }
  },

  tapEditUserinfo(){
    console.log("点击我的页面的编辑信息！")
    if(this.data.userInfo.avatar){
    //   let path='/pages/edituserinfo/edituserinfo?userInfo='+JSON.stringify(this.data.userInfo)
      let path='/pages/getuserinfo/index?userInfo='+JSON.stringify(this.data.userInfo)
      wx.navigateTo({
        url: path,
      })
    }
    else{
      wx.showToast({
        title: '请前往“我的”授权登录！',
        icon: "none",
        duration: 2000
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initMine()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
          selected: 4
        })
    }
    // 修改个人信息返回之后，需要刷新个人信息
    if(app.globalData.freshUserInfo){
      this.getMineData()
      app.globalData.freshUserInfo=false
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})